package com.example.starseas_phone;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


import com.example.starseas_phone.Utils.MySubject;
import com.example.starseas_phone.Utils.Utils_Schedule;
import com.zhuangfei.timetable.TimetableView;
import com.zhuangfei.timetable.listener.ISchedule;
import com.zhuangfei.timetable.listener.IWeekView;
import com.zhuangfei.timetable.listener.OnSlideBuildAdapter;
import com.zhuangfei.timetable.model.Schedule;
import com.zhuangfei.timetable.view.WeekView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainF1 extends Fragment implements View.OnClickListener {


    public static List<Utils_Schedule> list_schedule = new ArrayList<>();

    //模拟获取课程数据：自定义格式
    private List<MySubject> mySubjects;

    private static final String TAG = "MainF1";

    private LinearLayout mainf1_linear;
    private EditText mainf1_Classid;

    //控件
    private TimetableView mTimetableView;
    private WeekView mWeekView;

    private LinearLayout layout;
    private TextView titleTextView;
    private Button mainf1_btn;

    //记录切换的周次，不一定是当前周
    int target = -1;

//    private ProgressBar mainf1_progressbar;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.mainf1,container,false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initid();
        Log.d("list_schedule大小",list_schedule.size()+"");
        if (Sto.State==1){
            mainf1_linear.setVisibility(View.GONE);
            if (list_schedule.size()<=0){
//                progressing();
                find(Sto.students.getToken());
            }
        }else {
            if (Sto.teachers.getPositionId()==6){
                mainf1_linear.setVisibility(View.VISIBLE);
//                mainf1_progressbar.setVisibility(View.GONE);
            }else {
                mainf1_linear.setVisibility(View.GONE);
                if (list_schedule.size()<=0){
//                    progressing();
                    find(Sto.teachers.getToken());
                }
            }
        }
    }

//    private void progressing(){
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                while (list_schedule.size()==0){
//                    if(mainf1_progressbar.getProgress()==100){
//                        mainf1_progressbar.setProgress(0);
//                    }else {
//                        mainf1_progressbar.setProgress(mainf1_progressbar.getProgress()+1);
//                    }
//                }
//                if (list_schedule.size()!=0){
//                    getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            mainf1_progressbar.setVisibility(View.GONE);
//                        }
//                    });
//                }
//            }
//        }).start();
//    }

    private void initid(){
        mainf1_linear = (LinearLayout)getActivity().findViewById(R.id.mainf1_linear);
        mainf1_Classid = (EditText)getActivity().findViewById(R.id.mainf1_Classid);
        mainf1_btn = (Button) getActivity().findViewById(R.id.mainf1_btn);
        mainf1_btn.setOnClickListener(this);

        titleTextView = getActivity().findViewById(R.id.id_title);
        layout = getActivity().findViewById(R.id.id_layout);
        layout.setOnClickListener(this);
//        mainf1_progressbar = (ProgressBar) getActivity().findViewById(R.id.mainf1_progressbar);
    }

    private void initTimetableView() {
        //获取控件
        mWeekView = getActivity().findViewById(R.id.id_weekview);
        mTimetableView = getActivity().findViewById(R.id.id_timetableView);

        mTimetableView.source(mySubjects)
                .curWeek("2022-02-28 00:00:00")
                .curTerm("大二下学期")
                .monthWidthDp(40)
                .maxSlideItem(10)
                //透明度
                //日期栏0.1f、侧边栏0.1f，周次选择栏0.6f
                //透明度范围为0->1，0为全透明，1为不透明
//                .alpha(0.1f, 0.1f, 0.6f)
                .callback(new ISchedule.OnItemClickListener(){
                    @Override
                    public void onItemClick(View v, List<com.zhuangfei.timetable.model.Schedule> scheduleList) {
                        String a = titleTextView.getText().toString();
                        display(scheduleList,a);
                    }
                })
                .callback(new ISchedule.OnItemLongClickListener() {
                    @Override
                    public void onLongClick(View v, int day, int start) {
                        Toast.makeText(getActivity(),
                                "长按:周" + day  + ",第" + start + "节",
                                Toast.LENGTH_SHORT).show();
                    }
                })
                .callback(new ISchedule.OnWeekChangedListener() {
                    @Override
                    public void onWeekChanged(int curWeek) {
                        titleTextView.setText("第" + curWeek + "周");
                    }
                })
                //旗标布局点击监听
                .callback(new ISchedule.OnFlaglayoutClickListener() {
                    @Override
                    public void onFlaglayoutClick(int day, int start) {
                        mTimetableView.hideFlaglayout();
                        Toast.makeText(getActivity(),
                                "点击了旗标:周" + (day + 1) + ",第" + start + "节",
                                Toast.LENGTH_SHORT).show();

                    }
                })
                .isShowNotCurWeek(false)
                .showView();


        //设置周次选择属性
        mWeekView.source(mySubjects)
                .curWeek(mTimetableView.curWeek())
                .callback(new IWeekView.OnWeekItemClickedListener() {
                    @Override
                    public void onWeekClicked(int week) {
                        int cur = mTimetableView.curWeek();
                        //更新切换后的日期，从当前周cur->切换的周week
                        mTimetableView.onDateBuildListener()
                                .onUpdateDate(cur, week);
                        mTimetableView.changeWeekOnly(week);
                    }
                })
                .callback(new IWeekView.OnWeekLeftClickedListener() {
                    @Override
                    public void onWeekLeftClicked() {
                        onWeekLeftLayoutClicked();
                    }
                })
                .isShow(false)//设置隐藏，默认显示
                .showView();


        showTime();
    }

    protected void showTime() {
        String[] times = new String[]{
                "8:20", "9:15", "10:20", "11:15",
                "14:00", "14:50", "15:50", "16:50",
                "18:00","19:30"
        };
        OnSlideBuildAdapter listener= (OnSlideBuildAdapter) mTimetableView.onSlideBuildListener();
        listener.setTimes(times)
                .setTimeTextColor(Color.BLACK);
        mTimetableView.updateSlideView();
    }

    /**
     * 周次选择布局的左侧被点击时回调<br/>
     * 对话框修改当前周次
     */
    protected void onWeekLeftLayoutClicked() {
        final String items[] = new String[20];
        int itemCount = mWeekView.itemCount();
        for (int i = 0; i < itemCount; i++) {
            items[i] = "第" + (i + 1) + "周";
        }
        target = -1;
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("设置当前周");
        builder.setSingleChoiceItems(items, mTimetableView.curWeek() - 1,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        target = i;
                    }
                });
        builder.setPositiveButton("设置为当前周", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (target != -1) {
                    mWeekView.curWeek(target + 1).updateView();
                    mTimetableView.changeWeekForce(target + 1);
                }
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.id_layout:
                //如果周次选择已经显示了，那么将它隐藏，更新课程、日期
                //否则，显示
                if (mWeekView.isShowing()) {
                    mWeekView.isShow(false);
                    titleTextView.setTextColor(getResources().getColor(R.color.teal_200));
                    int cur = mTimetableView.curWeek();
                    mTimetableView.onDateBuildListener()
                            .onUpdateDate(cur, cur);
                    mTimetableView.changeWeekOnly(cur);
                } else {
                    mWeekView.isShow(true);
                    titleTextView.setTextColor(getResources().getColor(R.color.app_gold));
                }
                break;
            case R.id.mainf1_btn:
                String classid = mainf1_Classid.getText().toString();
                list_schedule.clear();
                findclass(classid);
                break;
        }
    }

    /**
     * 显示内容
     *
     * @param beans
     */
    protected void display(List<Schedule> beans, String a) {
        for (Schedule bean : beans) {
            String b = "第"+bean.getWeekList().get(0).toString()+"周";
            if (b.equals(a)){
                Showdialog(bean.getName(),bean.getRoom(),bean.getTeacher()+"",bean.getWeekList().get(0).toString()+"",bean.getStart());
                break;
            }
        }
    }

    private void find(String token){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient.Builder()
                            .connectTimeout(60, TimeUnit.SECONDS)//设置连接超时时间
                            .readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间
                            .build();
                    Request request = new Request.Builder()
                            .url(Sto.NetIP+"/api/Schedule/GetSchedultByToken?token="+token)
                            .build();
                    Response response = client.newCall(request).execute();
                    String a = response.body().string();
                    JSONObject jsonObject = new JSONObject(a);
                    String code = jsonObject.getString("code");
                    String msg = "";
                    if (code.equals("200")){
                        msg = jsonObject.getString("message");
                    }
                    else {
                        Log.d("数据","错误");
                    }
                    JSONArray jsonArray = new JSONArray(msg);
                    for (int i = 0;i<jsonArray.length();i++){
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                        String SchoolSemester = jsonObject1.getString("SchoolSemester");
                        int CollegeId = jsonObject1.getInt("CollegeId");
                        String ScheduleWeekly = jsonObject1.getString("ScheduleWeekly");
                        String ScheduleWeek = jsonObject1.getString("ScheduleWeek");
                        String ScheduleWhat = jsonObject1.getString("ScheduleWhat");
                        int WorkerId = jsonObject1.getInt("WorkerId");
                        String SchedulePlace = jsonObject1.getString("SchedulePlace");
                        String Course = jsonObject1.getString("Course");
                        int ClassId = jsonObject1.getInt("ClassId");
                        Utils_Schedule utils_schedule = new Utils_Schedule(SchoolSemester,CollegeId,ScheduleWeekly,ScheduleWeek,ScheduleWhat,WorkerId,SchedulePlace,Course,ClassId);
                        list_schedule.add(utils_schedule);
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            SubjectRepertory.parses(list_schedule);
                            Log.d("所有","完成");
                            mySubjects = SubjectRepertory.parses(list_schedule);
                            initTimetableView();
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void findclass(String classid){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient.Builder()
                            .connectTimeout(60, TimeUnit.SECONDS)//设置连接超时时间
                            .readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间
                            .build();
                    Request request = new Request.Builder()
                            .url(Sto.NetIP+"/api/Schedule/GetSchedultByClassId?classId="+classid)
                            .build();
                    Response response = client.newCall(request).execute();
                    String a = response.body().string();
                    JSONObject jsonObject = new JSONObject(a);
                    String message = jsonObject.getString("message");
                    Log.d("教务处",message);
                    if (message.equals("[]")) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(),"抱歉,没有该班级的课表信息!",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }else {
                        JSONArray jsonArray = new JSONArray(message);
                        for (int i = 0;i<jsonArray.length();i++){
                            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                            String SchoolSemester = jsonObject1.getString("SchoolSemester");
                            int CollegeId = jsonObject1.getInt("CollegeId");
                            String ScheduleWeekly = jsonObject1.getString("ScheduleWeekly");
                            String ScheduleWeek = jsonObject1.getString("ScheduleWeek");
                            String ScheduleWhat = jsonObject1.getString("ScheduleWhat");
                            int WorkerId = jsonObject1.getInt("WorkerId");
                            String SchedulePlace = jsonObject1.getString("SchedulePlace");
                            String Course = jsonObject1.getString("Course");
                            int ClassId = jsonObject1.getInt("ClassId");
                            Utils_Schedule utils_schedule = new Utils_Schedule(SchoolSemester,CollegeId,ScheduleWeekly,ScheduleWeek,ScheduleWhat,WorkerId,SchedulePlace,Course,ClassId);
                            list_schedule.add(utils_schedule);
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                SubjectRepertory.parses(list_schedule);
                                Log.d("所有","完成");
                                mySubjects = SubjectRepertory.parses(list_schedule);
                                initTimetableView();
                            }
                        });
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void Showdialog(String a,String b,String c,String d,int title){
        CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
        CustomDialog dialog =builder
                .style(R.style.CustomDialog)
                .cancelTouchout(true)
                .view(R.layout.dialog_custom)
                .build();
        dialog.show();
        TextView dialog_title = (TextView) dialog.findViewById(R.id.dialog_title);
        TextView textView1 = (TextView) dialog.findViewById(R.id.dialog_kc);
        TextView textView2 = (TextView) dialog.findViewById(R.id.dialog_dd);
        TextView textView3 = (TextView) dialog.findViewById(R.id.dialog_ls);
        TextView textView4 = (TextView) dialog.findViewById(R.id.dialog_jxz);
        textView1.setText(a);
        textView2.setText(b);
        textView3.setText(c);
        textView4.setText(d);
        switch (title){
            case 1:
                dialog_title.setText("上课时间: 08:20~10:00");
                break;
            case 3:
                dialog_title.setText("上课时间: 10:20~12:20");
                break;
            case 5:
                dialog_title.setText("上课时间: 14:00~15:40");
                break;
            case 7:
                dialog_title.setText("上课时间: 15:50~17:30");
                break;
        }
        Button button1 = (Button)dialog.findViewById(R.id.dialog_btn1);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

}
